import tkinter as tk
from tkinter import Toplevel
from tkinter import scrolledtext
from tkinter import UNITS
from time import *

class WinChat(Toplevel):
    def __init__(self):
        super(WinChat,self).__init__()
        self.title('聊天室')
        self.geometry('%dx%d' % (815,660))
        #self.resizable(False,False)
        self.create_widgets()

    def create_widgets(self):
        #聊天记录框
        self.scroll_chat = scrolledtext.ScrolledText(self,name='scroll_chat',width=70,height=27,font=("隶书",12))
        self.scroll_chat.tag_config('green',foreground='green')
        self.scroll_chat.grid(row=0,column=0,sticky=tk.E+tk.W,padx=10,pady=5)
        #用户信息框
        self.scroll_info = scrolledtext.ScrolledText(self,width=22,font=("隶书",12))
        self.scroll_info.tag_config('green', foreground='green')
        self.scroll_info.grid(row=0,column=1,sticky=tk.N+tk.S,padx=10,pady=5)
        #文本输入框
        self.scroll_edit = scrolledtext.ScrolledText(self,name='scroll_edit',height=10,font=("隶书",12))
        self.scroll_edit.grid(row=1,column=0,sticky=tk.E+tk.W,columnspan=2,padx=10,pady=5)
        #发送信息按钮
        self.button_send = tk.Button(self,name='button_send',text='发送(S)')
        self.button_send.grid(row=2,column=1,sticky=tk.E,padx=10,pady=5)

    #获取输入框内容
    def get_inputs(self):
        return self.scroll_edit.get(0.0,tk.END)

    #清空输入框内容
    def clear_inputs(self):
        self.scroll_edit.delete(0.0,tk.END)

    #添加信息到聊天区
    def append_message(self,sender,message):
        send_time = strftime('%Y-%m-%d %H:%M:%S',localtime(time()))
        sender_info = '%s：%s\n' % (sender,send_time)
        self.scroll_chat.insert(tk.END,sender_info,"green")
        self.scroll_chat.insert(tk.END,' '+ message + '\n')
        self.scroll_chat.yview_scroll(3,UNITS)

    #更新在线用户信息
    def update_onlineusers(self,onlineusers):
        self.scroll_info.delete(0.0,tk.END)
        self.scroll_info.insert(tk.END,'当前在线用户：\n',"green")
        self.scroll_info.insert(tk.END,onlineusers)

    #发送按钮触发事件
    def on_send_button_click(self,command):
        self.button_send['command'] = command

    def on_window_closed(self,command):
        self.protocol('WM_DELETE_WINDOW',command)



def command():
    msg = app.get_inputs()
    app.clear_inputs()
    app.append_message('我',msg)


if __name__ == '__main__':
    app = WinChat()
    app.on_send_button_click(command)
    app.mainloop()